package com.kunlong.util;

import app.support.exception.AppException;
import com.kunlong.base.utils.KunlongUtils;
import lombok.Data;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;

@Service
public class BookingBillServiceImpl implements BookingBillService {

	@Data
	public static class ParkingRule {
		String ruleContent;
		String remark;
		String ruleParams;
	}
	private static ScriptEngineManager scriptManager = new ScriptEngineManager();

	public static ScriptEngine getScriptEngine() {
		return scriptManager.getEngineByName("nashorn");//得到脚本引擎
	}

	@Override
	public BillResult bill(BillParam param) {
		String p = BookingBillServiceImpl.class.getResource("/conf/billcal.js").getPath();
		File f = new File(p);

		Math.ceil(1);
		ParkingRule rule = new ParkingRule(); //this.parkingRuleService.findByParkIdAndType(param.getParkId(), 1);
		try {
			rule.setRuleContent(FileCopyUtils.copyToString(new FileReader(f)));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		rule.setRemark("收费"); 		//rule.setRuleParams("{''freeMinutes'':''32'',''standardAmount'':''1'',''standardUnit'':30}");
		rule.setRuleParams("{'freeMinutes':10,'standardAmount':12,'standardUnit':60}".replaceAll("'","\""));
		Assert.notNull(rule, "规则不存在");
		if(StringUtils.isEmpty(rule.getRuleContent())) {
			throw new RuntimeException("未配置计费规则");
		}
		BillResult result = new BillResult();
		result.setRemark(rule.getRemark());
		try {
			ScriptEngine scriptEngine = getScriptEngine();
			scriptEngine.eval(rule.getRuleContent());
			try {
				Invocable invoc = (Invocable) scriptEngine;
				invoc.invokeFunction("cal", param,result,rule.getRuleParams());
			} catch (NoSuchMethodException e) {
				throw new RuntimeException("cal方法不存在");
			}
		} catch (ScriptException e) {
			throw new AppException("scriptError","脚本执行异常",e);
		}
		return result;
	}

	@Override
	public PayResult compute(PayParam param) {
		return null;
	}

	public static void testBookingTimeLong() {
		BillParam p = new BillParam();
		p.setParkId(1);
		p.setStartTime(new Date());
		p.setEndTime(new Date(new Date().getTime() + 3600000));

		BillResult r = new BookingBillServiceImpl().bill(p);
		String rr = KunlongUtils.toJSONStringPretty(r);

		System.out.println(rr);
		System.out.println( KunlongUtils.toJSONStringPretty(p));

	}

	public static void main(String[] args) {
		testBookingTimeLong();
	}
}
